#include <iostream>
#include <cmath>
using namespace std;
class Function {
public:
    virtual double operator () (double x) = 0;
};

class BisectionSolver {
protected:
    Function &F;
public:
    BisectionSolver(Function & F) : F(F) {}

    double solve(double l, double r) {
        const int max_calls = 40;
        const double tolerance_x = 1e-9;
        const double tolerance_y = 1e-12;

        double mid;
        double fl = F(l); 

        for (int i = 1; i < max_calls; ++i) { 
            
            // 检查区间长度是否足够小
            if (std::fabs(r - l) < tolerance_x) {
                return l + (r - l) / 2.0;
            }

            mid = l + (r - l) / 2.0;
            double f_mid = F(mid); 

            // 检查函数值是否足够小
            if (std::fabs(f_mid) < tolerance_y) {
                return mid;
            }
            
            // 根据函数值的符号决定下一步区间
            if (fl * f_mid < 0) {
                r = mid;
            } else {
                l = mid;
                fl = f_mid; // 更新左端点的函数值，避免重复计算
            }
        }
        
        // 达到最大调用次数，但未满足容差条件，返回当前中点
        mid = l + (r - l) / 2.0;
        cout << "Warning: Reached max function calls (" << max_calls << ") without meeting tolerance." << endl;
        cout << "Final approximate solution: " << mid << endl;
        return mid;
    }
};


